package com.osi.mes.qm.ftphandler;

import java.awt.Desktop;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPFilesHandler
{
	public static boolean uploadFile(String url, int port, String username, String password,
		String path, String filename, InputStream input)
		throws IOException
	{
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try
		{
			int reply;
			ftp.connect(
				url, port);
			ftp.login(
				username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply))
			{
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(path);
			FTPFile[] ftpFiles = ftp.listFiles();
			boolean flag = true;
			if (ftpFiles != null && ftpFiles.length > 0)
			{
				for (int i = 0; i < ftpFiles.length; i++)
				{
					FTPFile ftpFile = ftpFiles[i];
					if (filename.equals(ftpFile.getName()))
					{
						ftp.appendFile(
							filename, input);
						flag = false;
						break;
					}
				}
			}

			if (flag)
			{
				File f = new File(System.getProperty("user.dir") + "\\" + filename);
				if (!f.exists())
				{
					f.createNewFile();
				}
				FileInputStream fileInput = new FileInputStream(f);

				success = ftp.storeFile(
					filename, fileInput);
				if(success)
				{
					success = ftp.appendFile(
							filename, input);
				}
				if (f.exists())
					f.delete();
			}

			input.close();
			ftp.logout();
			success = true;
		}
		catch (IOException e)
		{
			throw e;
		}
		finally
		{
			if (ftp.isConnected())
			{
				try
				{
					ftp.disconnect();
				}
				catch (IOException ioe)
				{
				}
			}
		}
		return success;
	}
	
	// 上传单个文件
	public static boolean uploadFile(String url,int port,String username,String password,String path,String file,boolean isOverride) throws Exception
	{
		return uploadMutiplePics( url, port,username, password, path, new String[]{file},isOverride);
	}
	

	// 上传多个文件
	public static boolean uploadMutiplePics(String url, int port, String username, String password,
		String path, String[] files,boolean isOverride)
		throws Exception
	{
		boolean success = true;
		if (files == null || files.length == 0)
			return success;
		
		FTPClient ftp = null;

		try
		{
			ftp = loginToSpecifiedFTPPath(url,port,username,password,path);
			
			int fileIndex = ftp.listFiles().length;
			fileIndex++;
			for (int i = 0; i < files.length; i++)
			{
				try
				{
					String localFileName = files[i];
					FileInputStream inputStream = new FileInputStream(localFileName);
					if(isOverride)
					{
						int index = localFileName.lastIndexOf(File.separator);
						localFileName =localFileName.substring(index+1);
						success = ftp.storeFile(new String(localFileName.getBytes("GBK"),"iso-8859-1"), inputStream);
				    }
					else
					{
						success = ftp.storeFile(
								makeFileName(
									fileIndex++, localFileName), inputStream);
					}

					inputStream.close();
				}
				catch (IOException e)
				{
					success = false;
				}
			}

			ftp.logout();
		}
		catch (Exception e)
		{
			throw e;
		}
		finally
		{
			if (ftp.isConnected())
			{
				try
				{
					ftp.disconnect();
				}
				catch (IOException ioe)
				{
				}
			}
		}
		return success;
	}
	
	public static FTPClient loginToSpecifiedFTPPath(String url,int port,String username,String password,String path) throws SocketException, IOException
	{
		FTPClient ftp = new FTPClient();
		int reply;
		ftp.connect(
			url, port);
		ftp.login(
			username, password);
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply))
		{
			ftp.disconnect();
			return null;
		}

		ftp.setControlEncoding("utf-8");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftp.enterLocalPassiveMode();
		
		boolean isExist = false;
		FTPFile[] ftpDirs = ftp.listDirectories();
		for (int i = 0; i < ftpDirs.length; i++)
		{
			FTPFile ftpDir = ftpDirs[i];
			if (ftpDir.isDirectory() && ftpDir.getName().equals(
				path))
			{
				ftp.changeWorkingDirectory(path);
				isExist = true;
				break;
			}
		}

		if (!isExist)
		{
			boolean isSucc = ftp.makeDirectory(path);
			if (!isSucc)
				return null;
			ftp.changeWorkingDirectory(path);
		}
		
		return ftp;
	}

	public static String makeFileName(int index, String fileName)
	{
		String nameSufix = fileName.substring(fileName.lastIndexOf("."));
		if (index >= 0 && index < 10)
		{
			return "00" + index + nameSufix;
		}
		else if (index > 9 && index < 100)
		{
			return "0" + index + nameSufix;
		}
		else
			return index + nameSufix;
	}

	public static boolean downFile(String url, int port, String username, String password,
		String remotePath, String fileName, String localPath)throws IOException
	{
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try
		{
			int reply;
			ftp.connect(
				url, port);
			ftp.login(
				username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply))
			{
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);
			FTPFile[] fs = ftp.listFiles();
			boolean exists = false;
			for (FTPFile ff : fs)
			{
				if (ff.getName().equals(fileName))
				{
					File localFile = new File(localPath + "/" + ff.getName());

					OutputStream is = new FileOutputStream(localFile);
					ftp.retrieveFile(
						ff.getName(), is);
					is.close();
					exists = true;
				}
			}

			ftp.logout();
			success = exists;
		}
		catch (IOException e)
		{
			throw e;
		}
		finally
		{
			if (ftp.isConnected())
			{
				try
				{
					ftp.disconnect();
				}
				catch (IOException ioe)
				{
				}
			}
		}
		return success;
	}

	public static boolean deleteFile(String url, int port, String username, String password,
		String remotePath, String fileName)
		throws Exception
	{
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try
		{
			int reply;
			ftp.connect(
				url, port);
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(
				username, password);// 登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply))
			{
				ftp.disconnect();
				return success;
			}
			ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
			success = ftp.deleteFile(fileName);
			ftp.logout();
		}
		catch (Exception exp)
		{
			throw exp;
		}
		finally
		{
			if (ftp.isConnected())
			{
				try
				{
					ftp.disconnect();
				}
				catch (IOException ioe)
				{
				}
			}
		}

		return success;
	}

	public void testUpLoadFromDisk()
	{
		try
		{
			FileInputStream in = new FileInputStream(new File("D:/test.csv"));
			boolean flag;
			try
			{
				flag = uploadFile(
					"127.0.0.1", 21, "dell", "liting", "test", "test.csv", in);
				System.out.println(flag);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	public void testUpLoadFromString()
	{
		try
		{
			InputStream input = new ByteArrayInputStream("\ntest ftp\n".getBytes("utf-8"));
			boolean flag;
			try
			{
				flag = uploadFile(
					"127.0.0.1", 21, "dell", "liting", "test", "test.csv", input);
				System.out.println(flag);
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
	}

	public static void main(String[] args)
	{
		try
		{
			InputStream input = new ByteArrayInputStream("test ftp\n".getBytes("utf-8"));
			String[] files = new String[8];
			files[0] = "E:\\pic\\1.jpg";
			files[1] = "E:\\pic\\2.jpg";
			files[2] = "E:\\pic\\3.jpg";
			files[3] = "E:\\pic\\4.jpg";
			files[4] = "E:\\pic\\5.jpg";
			files[5] = "E:\\pic\\6.jpg";
			files[6] = "E:\\pic\\7.jpg";
			files[7] = "E:\\pic\\2.docx";
	
			FTPFilesHandler.uploadFile(
				"127.0.0.1", 21, "dell", "liting", "GMP", files[0],true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static void openFTPToSpecifiedDir(String host,String userName,String pwd,String dirName)
	{
		try
		{
			String ftpUser = URLEncoder.encode(
				userName, "UTF-8");
			String ftpPass = URLEncoder.encode(
				pwd, "UTF-8");
			String url = String.format(
				"ftp://%s:%s@"+host+"/"+dirName, ftpUser, ftpPass);
			URI uri = new URI(url);

			Desktop.getDesktop().browse(
				uri);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (URISyntaxException e)
		{
			e.printStackTrace();
		}
	}
}